package api

import (
	"goadmin/conf"
	"goadmin/dao"
	"goadmin/utils"

	"github.com/gin-gonic/gin"
)

type _appConfigRes struct {
	Register bool `json:"register"` // 是否允许注册
	Captcha  bool `json:"captcha"`  // 是否开启验证码
}

type _appEnableReq struct {
	Enable *bool `json:"enable" binding:"required"` // 如果直接使用bool，会导致false无法传递，所以使用指针
}

// @Tags app
// @Summary Get app config
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Success 200 {object} _appConfigRes
// @Router /api/apps/config [get]
func AppGetConfig(c *gin.Context) {
	resSuc(c, _appConfigRes{
		Register: conf.App.RegisterEnable,
		Captcha:  conf.App.CaptchaEnable,
	})
}

// @Tags app
// @Summary Change captcha enable
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param body body _appEnableReq true "Request Body"
// @Success 200 {object} resBody
// @Router /api/apps/captcha [put]
func AppChangeCaptchaEnable(c *gin.Context) {
	var body _appEnableReq
	if err := c.ShouldBindJSON(&body); err != nil {
		resInvalidBody(c)
		return
	}

	id := c.GetUint("user_id")
	user, err := dao.GetUserById(id)
	if err != nil {
		resNoAuth(c)
		return
	}
	if user.Auth != utils.AuthSuper {
		resPermissionDenied(c)
		return
	}

	if err := conf.SetCaptchaEnable(*body.Enable); err != nil {
		resFai(c, "Failed to change captcha enable")
		return
	}

	resSuc(c, nil)
}

// @Tags app
// @Summary Change register enable
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param body body _appEnableReq true "Request Body"
// @Success 200 {object} resBody
// @Router /api/apps/register [put]
func AppChangeRegisterEnable(c *gin.Context) {
	var body _appEnableReq
	if err := c.ShouldBindJSON(&body); err != nil {
		resInvalidBody(c)
		return
	}

	id := c.GetUint("user_id")
	user, err := dao.GetUserById(id)
	if err != nil {
		resNoAuth(c)
		return
	}
	if user.Auth != utils.AuthSuper {
		resPermissionDenied(c)
		return
	}

	if err := conf.SetRegisterEnable(*body.Enable); err != nil {
		resFai(c, "Failed to change register enable")
		return
	}

	resSuc(c, nil)
}
